package com.cedancp.hometrade;

import java.io.ByteArrayOutputStream;

import org.json.JSONException;
import org.json.JSONObject;

import com.cedancp.hometrade.EditPubicacion.editarPub;

import library.UserFunctions;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class UploadImage extends Activity {
	
	private static final int PICK_IMAGE = 1;
    ImageView imgView;
    Button btn_subir;
    Button btn_noSubir;
    Bitmap bitmap;
    Uri imageUri;
    private ProgressDialog pDialogo;
    UserFunctions userFunction = new UserFunctions();
    String cod_publicacion;
    String tipo;
    
    MediaPlayer mp=new MediaPlayer();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload_image);
		cod_publicacion=getIntent().getExtras().getString("cod_publicacion");
		tipo=getIntent().getExtras().getString("tipo");
		imgView=(ImageView) findViewById(R.id.imgView);
		btn_subir=(Button) findViewById(R.id.btn_subir);
		btn_noSubir=(Button) findViewById(R.id.btn_noSubir);
		
		//Evento para la imagen
		imgView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try{
				Intent gallery_intent=new Intent();
				gallery_intent.setType("image/*");
				gallery_intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(Intent.createChooser(gallery_intent, "Selecciona una imagen"), PICK_IMAGE);
				}catch(Exception e){
					Toast.makeText(getApplicationContext(),
			                e.getMessage(),
			                Toast.LENGTH_LONG).show();
			                Log.e(e.getClass().getName(), e.getMessage(), e);
				}
				
			}
		});
		
		//Evento para el boton de subir foto
		btn_subir.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(bitmap==null){
					Toast.makeText(getApplicationContext(),
                            "Por favor selecciona una imagen", Toast.LENGTH_SHORT).show();
				}
				else{
                    new ImageUploadTask().execute(cod_publicacion);
				}
				
			}
		});
		
		btn_noSubir.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (tipo.compareTo("cambiar")==0) {
					finish();
				}
				else{
					Intent i=new Intent(getApplicationContext(), ElegirMapa.class);
					i.putExtra("cod_publicacion", cod_publicacion);	
					startActivity(i);
					finish();
				}
				
			}
		});
		
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		Uri selectedImageUri = null;
		String filePath = null;
		
		if (resultCode == Activity.RESULT_OK) {
            selectedImageUri = data.getData();
        }
		
		if(selectedImageUri != null){
            try {
                String filemanagerstring = selectedImageUri.getPath();


                String selectedImagePath = getPath(selectedImageUri);

                if (selectedImagePath != null) {
                    filePath = selectedImagePath;
                } else if (filemanagerstring != null) {
                    filePath = filemanagerstring;
                } else {
                    Toast.makeText(getApplicationContext(), "Unknown path",
                            Toast.LENGTH_LONG).show();
                    Log.e("Bitmap", "Unknown path");
                }

                if (filePath != null) {
                    decodeFile(filePath);
                } else {
                    bitmap = null;
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Internal error",
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
		}
	}
	
	public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        cursor.moveToFirst();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
	
	public void decodeFile(String filePath) {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);
 
        final int REQUIRED_SIZE = 1024;
 
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }
 
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        bitmap = BitmapFactory.decodeFile(filePath, o2);
        imgView.setImageBitmap(bitmap);
 
    }
	
	class ImageUploadTask extends AsyncTask<String, String, JSONObject>{
		
		@Override
		public void onPreExecute(){
			super.onPreExecute();
			pDialogo=new ProgressDialog(UploadImage.this);
			pDialogo.setMessage("Subiendo imagen por favor espera...");
			pDialogo.setIndeterminate(false);
            pDialogo.setCancelable(false);
            pDialogo.show();
		}
		
		@Override
		protected JSONObject doInBackground(String... cod){
			String cod_pub=cod[0];
			BitmapFactory.Options bfo;
			ByteArrayOutputStream bao;
			
			bfo=new BitmapFactory.Options();
			bfo.inSampleSize=2;
			bao = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
			byte [] ba = bao.toByteArray();
			String ba1 = Base64.encodeToString(ba,Base64.DEFAULT);
			
			JSONObject json=userFunction.subirImg(ba1, cod_pub);
			
			return json;
			
		}
		
		@Override
		protected void onPostExecute(JSONObject json){
			pDialogo.dismiss();
			String error;
			String cod_publicacion;
			String mensaje="";
			int duration = Toast.LENGTH_SHORT;
			try {
				error = json.getString("error");
				if((error.compareTo("0"))==0){
					cod_publicacion=json.getString("cod_publicacion");
					mensaje="La imagen se subio existosamente";
					if (tipo.compareTo("cambiar")==0) {
						Intent i=new Intent(getApplicationContext(),EditPubicacion.class);
						i.putExtra("cod_publicacion", cod_publicacion);	
						startActivity(i);
						UploadImage.this.finish();
					}
					else{
						Intent i=new Intent(getApplicationContext(),ElegirMapa.class);
						i.putExtra("cod_publicacion", cod_publicacion);	
						startActivity(i);
						UploadImage.this.finish();
					}
				}
				else{
					mensaje=json.getString("error_msg");		
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			Toast toast = Toast.makeText(getApplicationContext(), mensaje, duration);
			toast.show();
			
		}
	}

}
